﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

namespace Our.Umbraco.uDbCompare
{
    public partial class OrphanedDocTemplate : System.Web.UI.UserControl
    {
        public bool UseRemoteConnectionString { get; set; }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
                BindData();
        }

        public void BindData()
        {
            if (SessionVars.IsValidDbConnection(UseRemoteConnectionString))
            {
                ShowOrphanedButton.Enabled = true;
            }
            else
            {
                ShowOrphanedButton.Enabled = false;
            }
        }

        protected void ShowOrphanedButton_OnClick(object sender, EventArgs e)
        {
            string legacyQuery = @"select d.nodeId as ContentNodeId, d.text as ContentName, n.path as ContentNodePath
                                    from cmsDocument d join umbracoNode n on d.nodeId = n.id left outer join cmsTemplate t on d.templateid = t.nodeid
                                    where t.nodeid is null and d.newest = 1 and d.templateid > 0
                                   ";
            DataTable orphanedTable = Db.QueryDb(legacyQuery, UseRemoteConnectionString);

            OrphanedGridView.DataSource = orphanedTable;
            OrphanedGridView.DataBind();

            NoResultsLabel.Visible = (orphanedTable.Rows.Count == 0);
        }

        protected void OrphanedGridView_OnRowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                DataRowView drv = e.Row.DataItem as DataRowView;

                int? contentNodeId = drv["ContentNodeId"] as Int32?;

                uDbCompareUI.SetLinkCell(uDbCompareUI.GetCellFromColumnName(e.Row, "ContentNodeId"),
                     contentNodeId.ToString(), uDbCompare.GetLinkUrl(LinkItem.Content, contentNodeId, UseRemoteConnectionString));

                TableCell contentNodePathCell = uDbCompareUI.GetCellFromColumnName(e.Row, "ContentNodePath");
                if (contentNodePathCell.Text.StartsWith("-1,-20,"))
                    uDbCompareUI.SetCellColour(contentNodePathCell, DbCompareMatch.Missing);
            }
        }
    }
}